/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package com.icerhe.trigger;

import com.icerhe.trigger.task.AlarmTask;
import com.icerhe.trigger.task.CronTask;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author icer
 *
 */
public class TaskProvider extends ContentProvider {
	
	private SQLiteOpenHelper dbHelper;
	
	private static final int CRONTASKS = 1;
	private static final int CRONTASKS_ID = 2;
	
	private static final UriMatcher sURLMatcher = new UriMatcher(
            UriMatcher.NO_MATCH);
	
    static {
        sURLMatcher.addURI("com.icerhe.trigger", "crontask", CRONTASKS);
        sURLMatcher.addURI("com.icerhe.trigger", "crontask/#", CRONTASKS_ID);
    }
    
    private static class DbHelper extends SQLiteOpenHelper {
    	private static final String DATABASE_NAME = "trigger.db";
        private static final int DATABASE_VERSION = 1;
        
        public DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        
        @Override
        public void onCreate(SQLiteDatabase db) {
        	Log.d(Consts.TAG, "TaskPrivoder.DbHelper onCreate: create sqlite datebase");
            db.execSQL("CREATE TABLE crontask (" +
                       CronTask.Columns.ID+ " INTEGER PRIMARY KEY," +
                       CronTask.Columns.TASK_TYPE+ " TEXT ," +
                       CronTask.Columns.TITLE+ " TEXT, " +
                       CronTask.Columns.DESCRIPTION+ " TEXT, " +
                       CronTask.Columns.CRON_PATTEN+ " TEXT, " +
                       CronTask.Columns.BY_DOW+ " INTEGER, " +
                       CronTask.Columns.STARTDATE+ " TEXT, " +
                       CronTask.Columns.ENDDATE+ " TEXT, " +
                       CronTask.Columns.ENABLED+ " INTEGER, " +
                       CronTask.Columns.EXTRA+ " TEXT);");

            // insert default alarms
            String insertMe = "INSERT INTO crontask " +
                    "(task_type, title, description, cron_patten, by_dow, startdate, enddate, enabled, extra) " +
                    "VALUES ";
            db.execSQL(insertMe + "('"+ AlarmTask.class.getName() +"', '测试提醒', '这个是每分钟触发一次', '* * * * * *', 1, NULL, NULL, 0, '{\"JSON\": \"Hello, World\"}');");
        }
        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
            Log.d("", "TaskPrivoder.DbHelper: Upgrading alarms database from version " +
                    oldVersion + " to " + currentVersion +
                    ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS crontask");
            onCreate(db);
        }
    }

	@Override
	public boolean onCreate() {
		dbHelper = new DbHelper(getContext());
		return true;
	}	
	
    @Override
    public String getType(Uri url) {
        int match = sURLMatcher.match(url);
        switch (match) {
            case CRONTASKS:
                return "vnd.android.cursor.dir/crontasks";
            case CRONTASKS_ID:
                return "vnd.android.cursor.item/crontasks";
            default:
                throw new IllegalArgumentException("Unknown URL");
        }
    }

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables("crontask");
		
		int match = sURLMatcher.match(uri);
		switch(match) {
			case CRONTASKS:
				break;
			case CRONTASKS_ID:
				qb.appendWhereEscapeString("_id=");
				qb.appendWhere(uri.getPathSegments().get(1));
				break;
			default:
				 throw new IllegalArgumentException("Unknown URL " + uri);
		}
		
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor ret = qb.query(db, projection, selection, selectionArgs,
                null, null, sortOrder);
        if (ret == null) {
            Log.d(Consts.TAG,"TaskProvider query failed");
        } else {
            ret.setNotificationUri(getContext().getContentResolver(), uri);
        }
        
		return ret;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
        if (sURLMatcher.match(uri) != CRONTASKS) {
            throw new IllegalArgumentException(
            		"TaskPrivider insert:Cannot insert into URI: " + uri);
        }
        ContentValues rowValues = new ContentValues(values);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insert("crontask", CronTask.Columns.DESCRIPTION, rowValues);
        if (rowId < 0) {
            throw new SQLException("Failed to insert row into " + uri);
        }
        Log.d(Consts.TAG, values.getAsString(CronTask.Columns.TASK_TYPE)+" added: rowId = " + rowId);
        
        Uri ret = ContentUris.withAppendedId(CronTask.CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(ret, null);
        
		return ret;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int count;
        long rowId = 0;
        int match = sURLMatcher.match(uri);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        switch (match) {
	        case CRONTASKS_ID: 
	            String segment = uri.getPathSegments().get(1);
	            rowId = Long.parseLong(segment);
	            count = db.update("crontask", values, "_id=" + rowId, null);
	            break;
	        default: 
	            throw new UnsupportedOperationException(
	                    "TaskProvider Update:Cannot update URI: " + uri);
        }
        
        Log.d(Consts.TAG, "update: rowId: " + rowId + " uri: "+uri);
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        long rowId = 0;
        switch (sURLMatcher.match(uri)) {
            case CRONTASKS:
                count = db.delete("crontask", where, whereArgs);
                break;
            case CRONTASKS_ID:
                String segment = uri.getPathSegments().get(1);
                rowId = Long.parseLong(segment);
                if (TextUtils.isEmpty(where)) {
                    where = "_id=" + segment;
                } else {
                    where = "_id=" + segment + " AND (" + where + ")";
                }
                count = db.delete("crontask", where, whereArgs);
                break;
            default:
                throw new IllegalArgumentException("TaskProvider delete:Cannot delete from URI: " + uri);
        }
        
        Log.d(Consts.TAG, 
        		"delete: rowId: " + rowId + 
        		" uri: " + uri +
        		"where: " +where);
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}


}
